/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiObjectNotFoundException;
import com.je.bpm.engine.delegate.event.ActivitiEventType;
import com.je.bpm.engine.delegate.event.impl.ActivitiEventBuilder;
import com.je.bpm.engine.impl.identity.Authentication;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.AttachmentEntity;
import com.je.bpm.engine.impl.persistence.entity.ByteArrayEntity;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.impl.util.IoUtil;
import com.je.bpm.engine.runtime.ProcessInstance;
import com.je.bpm.engine.task.Attachment;
import com.je.bpm.engine.task.Task;
import java.io.InputStream;


// Not Serializable

/**
 * 创建附件命令
 */
public class CreateAttachmentCmd implements Command<Attachment> {

    protected String attachmentType;
    protected String taskId;
    protected String processInstanceId;
    protected String attachmentName;
    protected String attachmentDescription;
    protected InputStream content;
    protected String url;

    public CreateAttachmentCmd(String attachmentType, String taskId, String processInstanceId, String attachmentName, String attachmentDescription, InputStream content, String url) {
        this.attachmentType = attachmentType;
        this.taskId = taskId;
        this.processInstanceId = processInstanceId;
        this.attachmentName = attachmentName;
        this.attachmentDescription = attachmentDescription;
        this.content = content;
        this.url = url;
    }

    @Override
    public Attachment execute(CommandContext commandContext) {
        if (taskId != null) {
            verifyTaskParameters(commandContext);
        }
        if (processInstanceId != null) {
            verifyExecutionParameters(commandContext);
        }
        AttachmentEntity attachment = commandContext.getAttachmentEntityManager().create();
        attachment.setName(attachmentName);
        attachment.setProcessInstanceId(processInstanceId);
        attachment.setTaskId(taskId);
        attachment.setDescription(attachmentDescription);
        attachment.setType(attachmentType);
        attachment.setUrl(url);
        attachment.setUserId(Authentication.getAuthenticatedUser().getDeptId());
        attachment.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime());

        commandContext.getAttachmentEntityManager().insert(attachment, false);

        if (content != null) {
            byte[] bytes = IoUtil.readInputStream(content, attachmentName);
            ByteArrayEntity byteArray = commandContext.getByteArrayEntityManager().create();
            byteArray.setBytes(bytes);
            commandContext.getByteArrayEntityManager().insert(byteArray);
            attachment.setContentId(byteArray.getId());
            attachment.setContent(byteArray);
        }

        commandContext.getHistoryManager().createAttachmentComment(taskId, processInstanceId, attachmentName, true);

        if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
            // Forced to fetch the process-instance to associate the right
            // process definition
            String processDefinitionId = null;
            if (attachment.getProcessInstanceId() != null) {
                ExecutionEntity process = commandContext.getExecutionEntityManager().findById(processInstanceId);
                if (process != null) {
                    processDefinitionId = process.getProcessDefinitionId();
                }
            }

            commandContext.getProcessEngineConfiguration().getEventDispatcher()
                    .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, attachment, processInstanceId, processInstanceId, processDefinitionId));
            commandContext.getProcessEngineConfiguration().getEventDispatcher()
                    .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_INITIALIZED, attachment, processInstanceId, processInstanceId, processDefinitionId));
        }

        return attachment;
    }

    protected TaskEntity verifyTaskParameters(CommandContext commandContext) {
        TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);

        if (task == null) {
            throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class);
        }

        if (task.isSuspended()) {
            throw new ActivitiException("It is not allowed to add an attachment to a suspended task");
        }

        return task;
    }

    protected ExecutionEntity verifyExecutionParameters(CommandContext commandContext) {
        ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(processInstanceId);

        if (execution == null) {
            throw new ActivitiObjectNotFoundException("Process instance " + processInstanceId + " doesn't exist", ProcessInstance.class);
        }

        if (execution.isSuspended()) {
            throw new ActivitiException("It is not allowed to add an attachment to a suspended process instance");
        }

        return execution;
    }

}
